package cn.sundat.web.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import cn.sundat.utils.UploadUtils;

public class FileUploadAction extends ActionSupport{
	
	//属性方式封装文件上传
	
	private File upload;
	private String uploadContentType;
	private String uploadFileName;
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	/**
	 * 文件的上传
	 * @return
	 * @throws IOException 
	 */
	public String add() throws IOException {
		//判断是否有文件上传
		if(uploadFileName!=null && !uploadFileName.trim().isEmpty()) {
			//上传文件的位置,为了安全，放到web-inf下面
			String fileName = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload");
			File file = new File(fileName);
			//判断文件夹是否存在,不存在就创建
			if(!file.exists() && !file.isDirectory()) {
				file.mkdir();
			}
			//为了防止重复，获取唯一的文件名
			String uuidName = UploadUtils.getUUIDName(uploadFileName);
			File newFile = new File(file, uuidName);
			//使用struts的功能上传
			FileUtils.copyFile(upload, newFile);
			//往数据库写入数据，先不写
			
		}
		return NONE;
	}
}
